package game.manager;

import game.Constants;
import game.Event;
import game.Event.EventType;

import java.util.Date;
import java.util.Observable;

public class CalendarManager extends Observable implements Manager {
	private Date previousMinute;
	private Date previousHour;

	private static CalendarManager manager;

	public static CalendarManager getManager() {
		if (manager == null)
			manager = new CalendarManager();
		return manager;
	}

	private CalendarManager() {
		this.initialize();
	}

	@Override
	public void update(Observable o, Object arg) {
		final Event event = (Event) arg;

		switch (event.getType()) {
		case RESET:
			this.initialize();
			break;
		}
	}

	@Override
	public void initialize() {
		final Date current = new Date();
		this.previousMinute = current;
		this.previousHour = current;
	}

	@Override
	public void gameUpdate() {
		final Date current = new Date();

		if (hasMinutePassed(current)) {
			EventManager.getManager().sendEvent(
					new Event(EventType.MINUTE_PASSED));
		}

		if (hasHourPassed(current)) {
			EventManager.getManager().sendEvent(
					new Event(EventType.HOUR_PASSED));
		}
	}

	private boolean hasHourPassed(Date current) {
		long difference = current.getTime() - previousHour.getTime();
		if (difference >= Constants.ONE_HOUR) {
			this.previousHour = current;
			return true;
		}
		return false;
	}

	private boolean hasMinutePassed(Date current) {
		long difference = current.getTime() - previousMinute.getTime();
		if (difference >= Constants.ONE_MINUTE) {
			previousMinute = current;
			return true;
		}
		return false;
	}

}
